package com.xywy.start;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.constants.ConstantValue;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyDialog;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;

/**
 * 快速注册
 * 
 * @author xiaogd
 */
public class RegisterActivity extends BaseActivity {
	private EditText name;
	private EditText mobile;
	private EditText password;
	private Button button;
	private ImageView nCancel;
	private ImageView mCancel;
	private ImageView pCancel;
	private Context mContext;

	MyProgress myProgress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.start_register);
		this.initView();
		this.preInit();

		this.loadData();
		this.setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	int sex;
	int height;
	String birthday;
	private int from;

	@Override
	public void preInit() {
		mContext = this.context;
		Intent intent = getIntent();
		sex = intent.getIntExtra("sex", 0);
		height = intent.getIntExtra("height", 0);
		birthday = intent.getStringExtra("birthday");
		from = intent.getIntExtra("from", 0);
		if (from == 1) {
			name.setText(this.getIntent().getStringExtra("account"));
			mobile.setText(this.getIntent().getStringExtra("mobile"));
			password.setText(this.getIntent().getStringExtra("password"));
		}
	}

	@Override
	public void loadData() {

	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.start_register_title_bar);
		TextView tvTitle = titleBar.getTitle();
		titleBar.getGo().setVisibility(View.INVISIBLE);
		titleBar.onClickBack(this);
		tvTitle.setText(getString(R.string.tv_start_register));

		name = (EditText) this.findViewById(R.id.et_start_register_name);
		mobile = (EditText) this.findViewById(R.id.et_start_register_mobile);
		password = (EditText) this
				.findViewById(R.id.et_start_register_password);
		nCancel = (ImageView) this.findViewById(R.id.iv_start_r_ncancel);
		mCancel = (ImageView) this.findViewById(R.id.iv_start_r_mcancel);
		pCancel = (ImageView) this.findViewById(R.id.iv_start_r_pcancel);

		button = (Button) this.findViewById(R.id.et_start_register_sendPwd);
	}

	String verifycationCode = "";
	/**
	 * 返回 密码
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.obj == null) {
				return;
			}
			String jsonStr = (String) msg.obj;
			if (jsonStr == null) {
				Toast.makeText(RegisterActivity.this, "发送验证码失败请重试",
						Toast.LENGTH_SHORT).show();
				return;
			}
			try {
				JSONObject json = new JSONObject(jsonStr);
				int resultcode = json.optInt("code");
				id = json.optString("id");
				if (resultcode == ResultCode.SUCCESSCODE) {
					startRegister();
				} else if (resultcode == 10014) {
					// JSONObject json = new JSONObject(jsonStr);
					final MyDialog myDialog = new MyDialog(
							RegisterActivity.this, R.style.MyDialogStyle);
					myDialog.show();
					myDialog.setContentView(R.layout.mydialog_twobutton_layout);
					TextView content = (TextView) myDialog
							.findViewById(R.id.mydialog_twobutton_layout_content_textView);
					content.setText("该手机已经注册，请登录");// json.optString("error")
					TextView leftButton = (TextView) myDialog
							.findViewById(R.id.mydialog_twobutton_layout_left_button);
					leftButton.setText("我知道了");
					myDialog.findViewById(
							R.id.mydialog_twobutton_layout_left_button)
							.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub

									myDialog.dismiss();
								}
							});
					TextView righButton = (TextView) myDialog
							.findViewById(R.id.mydialog_twobutton_layout_right_button);
					righButton.setText("立刻登录");
					myDialog.findViewById(
							R.id.mydialog_twobutton_layout_right_button)
							.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									myDialog.dismiss();
									SharedPreferences sp = context
											.getSharedPreferences("config",
													Context.MODE_PRIVATE);
									sp.edit()
											.putString("mobile",
													mobile.getText().toString())
											.commit();
									login();
									finish();
								}
							});

				} else {
					Toast.makeText(RegisterActivity.this,
							json.optString("error").toString(),
							Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			myProgress.stop();
			verifycationCode = (String) msg.obj;
		}

	};
	private String id;

	private void login() {
		Intent loginIntent = new Intent(this, LoginActivity.class);
		loginIntent.putExtra("from", 1);
		loginIntent.putExtra("sex", sex);
		loginIntent.putExtra("height", height);
		loginIntent.putExtra("birthday", birthday);
		// 名字
		loginIntent.putExtra("account", name.getText().toString().trim());
		// 手机号
		loginIntent.putExtra("mobile", mobile.getText().toString());
		// 密码
		loginIntent.putExtra("password", password.getText().toString());
		startActivity(loginIntent);
	}

	private void startRegister() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, ValidateCodeActivity.class);
		intent.putExtra("sex", sex);
		intent.putExtra("height", height);
		intent.putExtra("birthday", birthday);
		// 名字
		intent.putExtra("account", name.getText().toString());
		// 手机号
		intent.putExtra("mobile", mobile.getText().toString());
		// 密码
		intent.putExtra("password", password.getText().toString());
		intent.putExtra("id", id);

		intent.putExtra("target", ConstantValue.REGISTERVAL);
		startActivity(intent);
	}

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;

	// 处理网络请求
	public void sendMsg() {
		myProgress = new MyProgress(this, 10);
		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 请求路径
		paramsParser.action = getString(R.string.validate_sendCode);
		// 请求方式
		paramsParser.request = "get";

		// 请求参数
		params.put("target", mobile.getText().toString());
		params.put("type", 4);

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.context;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}

//		public <T extends Parser> void onNoNetWork(T paramParser, int resultCode) {
//			runOnUiThread(new Runnable() {
//				public void run() {
//					myProgress.stop();
//					Toast.makeText(RegisterActivity.this, "暂无网络连接",
//							Toast.LENGTH_SHORT).show();
//				}
//			});
//		};
	};

	private void setListener() {
		name.addTextChangedListener(nTextWatcher);
		mobile.addTextChangedListener(mTextWatcher);
		password.addTextChangedListener(pTextWatcher);
	}

	/** 名字 */
	boolean nFlag = false;
	TextWatcher nTextWatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence charSequence, int i, int i2,
				int i3) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void afterTextChanged(Editable editable) {
			if (editable.length() > 0) {
				nCancel.setVisibility(View.VISIBLE);
				nFlag = true;
				if (mFlag) {
					button.setBackgroundDrawable(RegisterActivity.this
							.getResources()
							.getDrawable(R.drawable.shape_button));
					button.setClickable(true);
				}
			} else {
				nCancel.setVisibility(View.INVISIBLE);
				nFlag = false;
				button.setBackgroundDrawable(RegisterActivity.this
						.getResources().getDrawable(
								R.drawable.shape_button_bgwhite));
				button.setClickable(false);
			}
		}
	};
	/** 手机号 */
	boolean mFlag = false;
	TextWatcher mTextWatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence charSequence, int i, int i2,
				int i3) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void afterTextChanged(Editable editable) {
			if (editable.length() > 0) {
				mCancel.setVisibility(View.VISIBLE);
				mFlag = true;
				if (nFlag) {
					button.setBackgroundDrawable(RegisterActivity.this
							.getResources()
							.getDrawable(R.drawable.shape_button));
					button.setClickable(true);
				}
			} else {
				mCancel.setVisibility(View.INVISIBLE);
				mFlag = false;
				button.setBackgroundDrawable(RegisterActivity.this
						.getResources().getDrawable(
								R.drawable.shape_button_bgwhite));
				button.setClickable(false);
			}
		}
	};
	boolean pFlag = false;
	TextWatcher pTextWatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence charSequence, int i, int i2,
				int i3) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void afterTextChanged(Editable editable) {
			if (editable.length() > 0) {
				pCancel.setVisibility(View.VISIBLE);
				pFlag = true;
				if (pFlag) {
					button.setBackgroundDrawable(RegisterActivity.this
							.getResources()
							.getDrawable(R.drawable.shape_button));
					button.setClickable(true);
				}
			} else {
				pCancel.setVisibility(View.INVISIBLE);
				pFlag = false;
				button.setBackgroundDrawable(RegisterActivity.this
						.getResources().getDrawable(
								R.drawable.shape_button_bgwhite));
				button.setClickable(false);
			}
		}
	};

	public void registerOnClick(View view) {
		switch (view.getId()) {
		case R.id.iv_start_r_ncancel:
			name.setText("");
			break;
		case R.id.iv_start_r_mcancel:
			mobile.setText("");
			break;
		case R.id.iv_start_r_pcancel:
			password.setText("");
			break;
		case R.id.et_start_register_sendPwd:
			next();
			break;
		}
	}

	private boolean compileExChar(String str) {

		String limitEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";

		Pattern pattern = Pattern.compile(limitEx);
		Matcher m = pattern.matcher(str);

		// if( m.find()){
		// }
		return m.find();

	}

	/**
	 * 验证判断
	 */
	boolean nSuccess = false, mSuccess = false, pSuccess = false;

	private void next() {
		/** 判断名字 */
		String nameStr = name.getText().toString().trim();
		if (compileExChar(nameStr)) {
			Toast.makeText(RegisterActivity.this, "用戶名不允许输入特殊符号！",
					Toast.LENGTH_SHORT).show();
			return;
		}

		int nchars = nameStr.toCharArray().length;
		int nbytes = nameStr.getBytes().length;
		int nLen = (nchars + nbytes) / 2;

		if (nLen >= 4 && nLen <= 16) {
			nSuccess = true;
		} else {
			Toast.makeText(context, this.getString(R.string.val_name_gz),
					Toast.LENGTH_SHORT).show();
			return;
		}
		/** 判断手机号 */
		String mobileStr = mobile.getText().toString().trim();
		int mchars = mobileStr.toCharArray().length;
		int mbytes = mobileStr.getBytes().length;
		int mLen = (mchars + mbytes) / 2;
		if (mLen == 11) {
			mSuccess = true;
		} else {
			Toast.makeText(context, this.getString(R.string.val_mobile_number),
					Toast.LENGTH_SHORT).show();
			return;
		}
		/** 判断密码 */
		String passwordStr = password.getText().toString().trim();
		int pchars = passwordStr.toCharArray().length;
		int pbytes = passwordStr.getBytes().length;
		int pLen = (pchars + pbytes) / 2;

		if (pLen >= 6) {
			pSuccess = true;
		} else {
			Toast.makeText(context, this.getString(R.string.val_password),
					Toast.LENGTH_SHORT).show();
			return;
		}

		if (nSuccess && mSuccess && pSuccess) {
			this.sendMsg();

		}

	}

}
